 //加载购物、支付进度条
var orderType = $("#orderType").val(); 
$(function(){
	//如果用户选择商品促销方式
	$(".addr_same .confirm_info .same_w [name=goodsSalePromotion]").change(function(){
		var $select =   $(this).parent().parent().find(".d").find("[name=wholeOrderPromotion]");
       //如果仍有其它商品参与活动仍不能参与店铺优惠活动
		if(productExistPromotion($(this))){
			$select.find("option[value='']").attr("selected",true);
			$select.attr("disabled",true); 
		}else{
			$select.attr("disabled",false); 
		}
		calculatePrice();
	});
	//如果用户选择店铺优惠促销方式
	$(".addr_same .confirm_info  .d [name=wholeOrderPromotion]").change(function(){
		var opt = $(this).val();
	    var $select = $(this).parent().parent().prevAll().find("[name=goodsSalePromotion]");
        if(opt == ""){                
        	$select.attr("disabled",false); 
        }else{
        	$select.find("option[value='']").attr("selected",true);
        	$select.attr("disabled",true); 
        }
		calculatePrice();
	});

	//判断同一店铺的其它商品是否有选中的优惠活动 存在true,不存在false
	function productExistPromotion($obj){
		var flag = false;
		if($obj.val() != ""){
			return true;
		}
       //  $obj.parent().siblings(".same_w").find("select").each(function(){
		 $obj.parent().parent().find(".same_w").find("select").each(function(){
    	    if($(this).val() != ""){
          	   flag = true;
    	    }
	     });
		return  flag;
	}
	
	//提交订单
	$(".payment").click(function(){
		var url = rootPath + "/order/generateOrders";
		if(!CommnUtil.notNull($("#addressId").val())){
			alert("发货地址不能为空!");
			return false;
		}
		var data =getPostData();
		var index = layer.load(5,{offset: ['50%', '40%']});//进度条 遮罩
		var result = CommnUtil.ajax(url,{"param":data}, "json");
		if (result.resultSuccess) {//提交订单成功
			 Pause(this,6000);//调用暂停函数
	 	     this.NextStep=function(){
	 			window.close();
	 	     }
			var $url = rootPath + '/order/card_pay';
			window.open($url,'_blank');
		}else if(result.sessionValid){
			 reLogin();
		} else {
			 layer.msg("订单提交失败",{icon:2,skin: 'layui-layer-red ',offset: ['40%', '45%']});
			 Pause(this,6000);//调用暂停函数
	 	     this.NextStep=function(){
	 	    	 window.location.href = rootPath + "/";
	 	     }
		}
		
	});
 });
//请求生成订单的数据
function getPostData(){
	var data = {};
    var shops =[]; //支持多店铺
    data["source"] ="1"; //订单来源 1：pc平台；2：手机触屏；3：微信商城	
	data["maId"] = $("#addressId").val(); //收货地址ID
	data["memberId"] =member.mId; //会员ID
	data["cartId"] ="";//来自购物车提交的商品
	
    //遍历所有店铺
	$(".addr_same .confirm_info .nine").each(function(){
	    var shop = {};
	    var products = []; //订单商品集合
		shop["sellerId"] = $(this).find("#sellerId").val(); //店铺ID
		if($(this).find("[name=wholeOrderPromotion]").find("option:selected")){
			shop["proDetailId"] = $(this).find("[name=wholeOrderPromotion]").find("option:selected").attr("value"); //用户选择参与的店铺促销活动ID
		}
		shop["memo"] = $(this).find("#memeo").val();
		shop["expressId"] = $(this).find(".expressList").find("option:selected").attr("value");
		$(this).find(".same_w").each(function(){
			var product={};
			product["productId"] = $(this).attr("id");
			product["quantity"] = $(this).find(".mWord").text();
		    product["goods_sku_id"] = $(this).attr("goods_sku_id");
		    if($(this).find("[name=goodsSalePromotion]").find("option:selected")){
		    	product["proDetailId"] = $(this).find("[name=goodsSalePromotion]").find("option:selected").attr("value"); //商品参与促销活动ID
			}
		    products.push(product);
		});
		shop["products"] = products;
		shops.push(shop);
	});
	data["shops"] = shops;	
	return JSON.stringify(data);
}
//重新登录页面
 function reLogin(){
 	window.location.href=rootPath + '/member/loginPre?redirect=/cart/cartPage?cartType=all';
 }
//计算整个订单中商品小计价格、店铺价格、优惠价格、多店铺总价格
function calculatePrice(){
	/*debugger;*/
	var $allTotalAmount =0; //订单总金额
	var $orderDiscountAmount = 0;//整笔订单优惠金额
    //遍历所有店铺
	$(".addr_same .confirm_info .nine").each(function(){
		var $shopDiscountAmount = 0;//整笔订单优惠金额
		var $total_price = 0 ; //店铺总金额
		var $promotion_money = 0; //店铺优惠金额
		var $fee = $(this).find(".expressFee").text()*1;
		$total_price += $fee;
		var $goodsDiscountAmount =0;//记录该店铺下所有商品参与的优惠活动的优惠金额
	    //遍历店铺下的所有商品
		$(this).find(".unit_price").each(function(i,item){
		//	alert($(this).html());
			var $price = 0;	//商品小计
			var $unit_price = parseFloat($(this).text());
			var $number = $(this).parents(".same_w").find(".count").find("p").text()*1;
			$price = ($number * $unit_price).toFixed(2);	
			//商品优惠活动
			var $goodsPro = $(this).parents(".same_w").find("select[name='goodsSalePromotion']").children('option:selected');
			if($goodsPro){
				var $discountAmount = pro($price,$goodsPro)*1;//计算商品参与促销后优惠金额
				$goodsDiscountAmount += $discountAmount;
			}
			
			$price = $price -$discountAmount; //商品小计价格 ;去除商品优惠价格
			
			$(this).parents(".same_w").find(".price").text($price.toFixed(2));
			$total_price += $price*1;
		});
		
		//店铺优惠活动
		var $shopPro = $(this).find("select[name='wholeOrderPromotion']").children('option:selected');
		if($shopPro){
			$shopDiscountAmount += pro($total_price,$shopPro);//计算店铺参与促销后的店铺优惠金额
		}	
		$total_price = parseFloat($total_price) -parseFloat($shopDiscountAmount); //去除店铺优惠价格	
		$allTotalAmount += $total_price;
		$(this).find(".total_price").text('￥' + $total_price.toFixed(2));	//店铺总金额
		var $total =parseFloat($shopDiscountAmount) + parseFloat($goodsDiscountAmount);
	    $(this).find(".promotion_money").text($total.toFixed(2)); //店铺合计优惠	
		$orderDiscountAmount += parseFloat($shopDiscountAmount);
		
	});
	$(".promotion_totalAmount_money").text($orderDiscountAmount.toFixed(2));  //整单优惠
	$("#allTotalAmount").text('￥' + $allTotalAmount.toFixed(2));
	
}
function pro($totalPrice,$obj){
	var proType = $obj.attr("protype"); 
    var $discountAmount = 0;
    var $discountRate = 0;
	if('0' == proType || '1' == proType ){ //订单满减或 商品满减
		$discountAmount = $obj.attr("discountamount")*1;
    }else if('2' == proType){//商品满赠
		 return 0;
	}else if('3' == proType){//商品打折
		 $discountRate = $obj.attr("discountrate")*1;
		 $discountAmount = $totalPrice*(1-$discountRate);		
	}else{
		 return 0;
	}
	return $discountAmount.toFixed(2);
}
